(ns amsi.server.server
  (:import (java.net ServerSocket Socket))
  (:require [amsi.common.logging :as logger])
  (:require [amsi.common.socket :as socket]))

(defn start-socket-agent
  "Creates and start agent for processing client's input. Streams means socket, input and output streams. F is function for handling client input"
  [streams f args]
  (let[socket-agent (agent streams)]
    (logger/log "starting socket agent")
    (send socket-agent f args)))

(defn accept-socket
  "Accept socket and startc agent for handling socket"
  [socket f args]
  (let [streams (socket/open-socket socket)]
    (start-socket-agent streams f args)))

;Start server on specif port.
(defn listen
  "Start server on specified port"
  [port f args]
  (let[server-socket (ServerSocket. port)]
    ((logger/log "server started on port" port)      
      (loop[server-socket server-socket]        
        (accept-socket (.accept server-socket) f args)          
          (recur server-socket)))))






